using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ComponentModel;
using System.Data;
using ACME.Northwind.DataTransfer;
using ACME.Northwind.Business.Objects;
using Widgetsphere.Core.DataAccess;
using System.Linq.Expressions;
using ACME.Northwind.Business.LINQ;
using Widgetsphere.Core.Util;

namespace ACME.Northwind.DALProxy.Extensions
{
	/// <summary>
	/// This is a set of extensions for the Shipper DAL/DTO object
	/// </summary>
	public static partial class ShipperExtension
	{
		#region Fill DAL

		/// <summary>
		/// Populate a DAL object from its corresponding DTO.
		/// </summary>
		/// <param name="item">The empty DAL object.</param>
		/// <param name="dtoItem">The source DTO to load.</param>
		public static void Fill(this Shipper item, ShipperDTO dtoItem)
		{
			if (dtoItem == null) throw new Exception("The Shipper DTO cannot be null.");
			if (item == null) throw new Exception("The Shipper item cannot be null.");
			DataRow dr = ((DataRow)((IWrappingClass)item).WrappedClass);
			dr["ShipperID"] = dtoItem.ShipperId;
			if (dtoItem.Phone == null) dr["Phone"] = System.DBNull.Value;
			else dr["Phone"] = dtoItem.Phone;
			dr["CompanyName"] = dtoItem.CompanyName;
		}

		#endregion

		#region Fill DTO

		/// <summary>
		/// Populate a DTO object collection from its corresponding DAL object collection.
		/// </summary>
		/// <param name="list">The destination DTO collection.</param>
		/// <param name="shipperCollection">The source DAL collection.</param>
		public static void Fill(this List<ShipperDTO> list, ShipperCollection shipperCollection)
		{
			if (shipperCollection == null) throw new Exception("The Shipper collection cannot be null.");
			if (list == null) list = new List<ShipperDTO>();
			foreach (Shipper item in shipperCollection)
			{
				ShipperDTO newItem = new ShipperDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Populate a DTO object from its corresponding DAL object.
		/// </summary>
		/// <param name="item">The source DAL object.</param>
		/// <param name="dtoItem">The empty DTO to load.</param>
		public static void Fill(this ShipperDTO dtoItem, Shipper item)
		{
			if (dtoItem == null) throw new Exception("The Shipper DTO cannot be null.");
			if (item == null) throw new Exception("The Shipper item cannot be null.");
			dtoItem.ShipperId = item.ShipperId;
			dtoItem.Phone = item.Phone;
			dtoItem.CompanyName = item.CompanyName;
			dtoItem.CreatedDate = item.CreatedDate;
			dtoItem.CreatedBy = item.CreatedBy;
			dtoItem.ModifiedDate = item.ModifiedDate;
			dtoItem.ModifiedBy = item.ModifiedBy;
		}

		#endregion

		#region RunSelect

		/// <summary>
		/// Select all objects from store.
		/// </summary>
		public static void RunSelect(this List<ShipperDTO> list)
		{
			if (list == null) list = new List<ShipperDTO>();
			ShipperCollection retval = ShipperCollection.RunSelect();
			foreach (Shipper item in retval)
			{
				ShipperDTO newItem = new ShipperDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<ShipperDTO> list, Expression<Func<ShipperQuery, bool>> where)
		{
			if (list == null) list = new List<ShipperDTO>();
			list.Fill(ShipperCollection.RunSelect(where));
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a paged result set.
		/// </summary>
		public static PagedQueryResults<ShipperDTO> RunSelect(this List<ShipperDTO> list, string pageSize, string page, string sortOrder, string sortColumn, string linq)
		{
			if (list == null) list = new List<ShipperDTO>();
			#region Setup Variables and Error Check
			int po;
			int rpp;

			if (!int.TryParse(page, out po)) throw new Exception("The page number number is not a valid integer!");
			if (po < 1) po = 1;

			if (!int.TryParse(pageSize, out rpp)) throw new Exception("The page size is not a valid integer!");
			if (rpp < 1) rpp = 1;

			Shipper.FieldNameConstants sortField;
			try
			{
				sortField = (Shipper.FieldNameConstants)Enum.Parse(typeof(Shipper.FieldNameConstants), sortColumn);
			}
			catch
			{
				throw new Exception("The sort field is not valid!");
			}

			bool ascending = (sortOrder.ToLower() == "asc" || sortOrder.ToLower() == "ascending");
			#endregion

			PagedQueryResults<ShipperDTO> retVal = new PagedQueryResults<ShipperDTO>();
			ShipperPaging paging = new ShipperPaging();
			paging.RecordsperPage = rpp;
			paging.PageIndex = po;
			paging.OrderByList.Add(new ShipperPagingFieldItem(sortField, ascending));

			ShipperCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = ShipperCollection.RunSelect(x => true, paging);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodPaged(linq, "ACME.Northwind.Business", "Shipper");
				dalList = (ShipperCollection)method.Invoke(null, new object[] { paging });
			}

			if (list == null) list = new List<ShipperDTO>();
			foreach (Shipper item in dalList)
			{
				ShipperDTO newItem = new ShipperDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}

			retVal.CurrentPage = paging.PageIndex;
			double totalPages = Math.Ceiling((double)paging.RecordCount / (double)paging.RecordsperPage);
			retVal.TotalPages = (int)totalPages;
			retVal.TotalRecords = paging.RecordCount;
			retVal.GridData = list;

			return retVal;
		}

		#endregion

		#region RunSelect Paged

		/// <summary>
		/// Using the specified Where expression, execute a query against the database to return a result set.
		/// </summary>
		public static void RunSelect(this List<ShipperDTO> list, string linq)
		{
			if (list == null) list = new List<ShipperDTO>();

			ShipperCollection dalList = null;
			if (string.IsNullOrEmpty(linq))
			{
				dalList = ShipperCollection.RunSelect(x => true);
			}
			else
			{
				System.Reflection.MethodInfo method = LINQDynamicCompile.GetLINQMethodAll(linq, "ACME.Northwind.Business", "Shipper");
				dalList = (ShipperCollection)method.Invoke(null, new object[] { });
			}

			if (list == null) list = new List<ShipperDTO>();
			foreach (Shipper item in dalList)
			{
				ShipperDTO newItem = new ShipperDTO();
				newItem.Fill(item);
				list.Add(newItem);
			}
		}

		#endregion

		#region Persist

		/// <summary>
		/// Persists this object to store.
		/// </summary>
		public static ShipperDTO Persist(this ShipperDTO shipper)
		{
			if (shipper == null) throw new Exception("The Shipper DTO cannot be null.");
			//Find this object and if not exists, create a new one
			Shipper newItem = null;
			ShipperCollection newCollection = null;

			bool isIdentityChecked = false;
			isIdentityChecked = true;
			if(isIdentityChecked)
			{
				if (shipper.ShipperId > 0)
				{
					newItem = ACME.Northwind.Business.Objects.Shipper.SelectUsingPK(shipper.ShipperId);
					newCollection = newItem.ParentCollection;
				}
				else
				{
					if (shipper.ShipperId == 0) shipper.ShipperId = -1;
					newCollection = new ShipperCollection();
					newItem = newCollection.NewItem();
				}
			}
			else
			{
				newItem = ACME.Northwind.Business.Objects.Shipper.SelectUsingPK(shipper.ShipperId);
				if (newItem == null)
				{
					newCollection = new ShipperCollection();
					newItem = newCollection.NewItem();
				}
				else
				{
					newCollection = newItem.ParentCollection;
				}
			}

			//Populate the DAL and perist
			newItem.Fill(shipper);
			if (!newItem.IsParented) newCollection.AddItem(newItem);
			newCollection.Persist();

			//Re-populate the passed-in object from the DAL
			shipper.Fill(newItem);
			return shipper;
		}

		/// <summary>
		/// Persists this collection to store.
		/// </summary>
		public static bool Persist(this List<ShipperDTO> shipperList)
		{
			if (shipperList == null) throw new Exception("The Shipper DTO list cannot be null.");
			//Get all objects from the database that match PK
			ShipperCollection shipperCollection = new ShipperCollection();
			List<ShipperPrimaryKey> keyList = new List<ShipperPrimaryKey>();
			foreach (ShipperDTO dto in shipperList)
			{
				keyList.Add(new ShipperPrimaryKey(dto.ShipperId));
			}			
			shipperCollection.SubDomain.AddSelectCommand(new ACME.Northwind.Business.SelectCommands.ShipperSelectByPks(keyList));
			shipperCollection.SubDomain.RunSelectCommands();

			//Now find and populate the objects for saving
			foreach (ShipperDTO dto in shipperList)
			{
				Shipper shipper = (from x in (IEnumerable<Shipper>)shipperCollection
					where x.ShipperId == dto.ShipperId
					select x).FirstOrDefault();

				if (shipper == null) shipper = shipperCollection.NewItem();
				shipper.Fill(dto);
				if (!shipper.IsParented) shipperCollection.AddItem(shipper);
			}
			shipperCollection.Persist();

			//Re-populate the passed-in object from the DAL
			List<ShipperDTO> deletedList = new List<ShipperDTO>();
			foreach (ShipperDTO dto in shipperList)
			{
				Shipper shipper = (from x in (IEnumerable<Shipper>)shipperCollection
					where x.ShipperId == dto.ShipperId
					select x).FirstOrDefault();

				if (shipper != null) dto.Fill(shipper);
				else deletedList.Add(dto);
			}

			//Remove the items that are no longer there (if any)
			foreach (ShipperDTO dto in deletedList)
			{
				shipperList.Remove(dto);
			}

			return true;
		}

		#endregion

		#region Shipper Select by Column

		#endregion

		#region Shipper SelectUsingPK

		/// <summary>
		/// Select a single object from this collection by its primary key.
		/// </summary>
		public static bool SelectUsingPK(this ShipperDTO shipper, int shipperid)
		{
			Shipper item = ACME.Northwind.Business.Objects.Shipper.SelectUsingPK(shipperid);
			if (item == null) return false;
			shipper.Fill(item);
			return true;
		}

		#endregion

		#region Shipper Select By Foreign Key

		#endregion

		#region Shipper Delete

		/// <summary>
		/// Delete the specified item
		/// </summary>
		public static bool Delete(this ShipperDTO shipper)
		{
			Shipper item = ACME.Northwind.Business.Objects.Shipper.SelectUsingPK(shipper.ShipperId);
			if (item == null) return false;
			item.Delete();
			item.Persist();
			return true;
		}

		#endregion
	}

}
